package com.manshutingyu.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.manshutingyu.common.core.constants.SecurityConstants;
import com.manshutingyu.common.core.properties.MySecurityProperties;
import com.manshutingyu.common.core.utils.StringUtils;
import com.manshutingyu.gateway.properties.IgnoreWhiteProperties;
import com.manshutingyu.gateway.utils.WebFluxUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关鉴权
 *
 * @Author：yinyuxia
 * @Date：2025/4/27 11:09
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    // 排除过滤的 uri 地址，nacos自行添加
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;
    @Resource
    private MySecurityProperties mySecurityProperties;
   // public static final String secretKey="";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        String url = request.getURI().getPath();
        // 跳过不需要验证的路径
        if (StringUtils.matches(url, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }
        // 获取请求token
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        // 如果请求头中没有Authorization信息，或者Authorization以Bearer开头，则认为是匿名用户
        if (StrUtil.isBlank(token) || !token.startsWith(SecurityConstants.JWT_TOKEN_PREFIX)) {
            return unauthorizedResponse(exchange, "令牌不能为空");
        }
        // 去除 Bearer 前缀
        token = token.substring(SecurityConstants.JWT_TOKEN_PREFIX.length());
        // 解析 Token
        JWT jwt = JWTUtil.parseToken(token);

        // 检查 Token 是否有效(验签 + 是否过期)
        boolean isValidate = jwt.setKey(mySecurityProperties.getJwt().getKey().getBytes()).validate(0);
        if (!isValidate) {
            log.error("JwtValidationFilter error: token is invalid");
            return unauthorizedResponse(exchange, "令牌已过期或验证不正确");
        }
        JSONObject payloads = jwt.getPayloads();
        String username = payloads.getStr(JWTPayload.SUBJECT);
        if (StringUtils.isEmpty(username)) {
            return unauthorizedResponse(exchange, "令牌验证失败");
        }

        // 设置用户信息到请求
       /* addHeader(mutate, SecurityConstants.USER_KEY, userkey);
        addHeader(mutate, SecurityConstants.DETAILS_USER_ID, userid);*/
        addHeader(mutate, SecurityConstants.DETAILS_USERNAME, username);
        // 内部请求来源参数清除
        removeHeader(mutate, SecurityConstants.FROM_SOURCE);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = WebFluxUtils.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    private void removeHeader(ServerHttpRequest.Builder mutate, String name) {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
        log.error("[鉴权异常处理]请求路径:{},错误信息:{}", exchange.getRequest().getPath(), msg);
        return WebFluxUtils.webFluxResponseWriter(exchange.getResponse(), msg, HttpStatus.UNAUTHORIZED.value());
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
